using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Globalization;

namespace Camalon.Drawing
{
	/// <summary>
	/// Summary description for SizeFConverter.
	/// </summary>
	public class ShapeCombineConverter:ExpandableInstanceConverter
	{

		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			
			if ( value is string ) 
			{ 
				string sVal = (string)value;
				if( sVal.Length == 0 || sVal.ToLower().Trim() == "empty" ) return ShapeCombine.Empty;
				string[] args = sVal.Split(';');

				if( args.Length < 2 ) throw new InvalidOperationException("Invalid value entered");	

				Shape arg0 = null;
				string name = string.Empty;
				bool bShapeFound = args[0].ToLower().Trim() == "(null)";
				if( !bShapeFound)
				{
						foreach( Shape shape in context.Container.Components)
					{
						if( args[0] == TypeDescriptor.GetComponentName( shape )) 
						{ arg0 = shape;bShapeFound = true; break; }
					}
				}

				if( !bShapeFound )
					throw new InvalidOperationException("Invalid shape value entered");
	
				try
				{
					ShapeCombineMode arg1 = (ShapeCombineMode) Enum.Parse(typeof(ShapeCombineMode), args[1], true);
					return new ShapeCombine( arg0, arg1);
				}
				catch
				{
					throw new InvalidOperationException("Invalid ShapeCombineMode entered");
				}
			
				//return context.PropertyDescriptor.GetValue( context.Instance);

			}

			return base.ConvertFrom (context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{

			if( value is ShapeCombine )
			{
				ShapeCombine m = (ShapeCombine) value;
				if (destinationType == typeof(string)) 
				{
					//return "(ShapeCombine)";
					if( m.IsEmpty) return "Empty";
					else return String.Format( "{0};{1}", m.Shape == null ? "(null)":TypeDescriptor.GetComponentName( m.Shape ) ,m.Mode);
				}

				if (destinationType == typeof(InstanceDescriptor) ) 
				{
					ConstructorInfo ctor = typeof(ShapeCombine).GetConstructor(new Type[] {typeof(Shape), typeof(ShapeCombineMode)});
					if (ctor != null) return new InstanceDescriptor(ctor, new object[] {m.Shape,m.Mode});
				}
			}
			
			return base.ConvertTo (context, culture, value, destinationType);
		}


	}

}
